/**
* 溯源管理表单
* huangjianhong
* 2023/5/26
*/

<template>
  <el-dialog :visible.sync="formDialog" :width="dialogWidth" custom-class="input-dialog" @close="closeDialog" :title="title">
    <el-form :model="form" ref="form" status-icon :label-width="labelWidth" :rules="rules">
      <el-form-item
        v-for="(item, index) in labelList"
        :key="'formItem-' + index"
        :label="item.label + '：'"
        :prop="item.prop"
        :required="item.required"
        :rules="[{ required: item.required, message: inputRuleArr.includes(item.type) ? `请输入${item.label}` : `请选择${item.label}` }]">
        <!--输入框-->
        <el-input v-if="item.type === 'input'" v-model="form[item.prop]" :disabled="item.disabled" placeholder="请输入"></el-input>
        <!--单选下拉框-->
        <el-select v-else-if="item.type === 'select'" v-model="form[item.prop]" :disabled="item.disabled" filterable @change="change($event, item)">
          <el-option v-for="(element, i) in item.select" :key="i" :label="element.label" :value="element.value"></el-option>
        </el-select>
        <!--多选下拉框-->
        <el-select v-else-if="item.type === 'multipleSelect'" v-model="form[item.prop]" :disabled="item.disabled" multiple @change="multipleChange($event, item)">
          <el-option v-for="(element, i) in item.select" :key="i" :label="element.label" :value="element.value"></el-option>
        </el-select>
        <!--日期选择器-->
        <el-date-picker v-else-if="item.type === 'date'" v-model="form[item.prop]" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" @change="changeDate"></el-date-picker>
        <!--图片；图片上传-->
        <div v-else-if="item.type === 'image'" class="image-upload-wrap">
          <el-image v-if="form[item.prop]" :src="form[item.prop]" class="avatar" :preview-src-list="[form[item.prop]]"></el-image>
          <el-upload v-else class="avatar-uploader" :headers="headers" :action="action" :show-file-list="false"
                     :on-success="(response, file, fileList)=>{return handleImgSuccess(response, file, fileList, index)}"
                     :before-upload="beforeImgUpload">
            <img v-if="form[item.prop]" :src="form[item.prop]" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <i v-if="form[item.prop]" class="el-icon-remove" @click.stop="()=>{return imageRemove(index)}"></i>
        </div>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button @click="submit" type="primary">确定</el-button>
      <el-button v-if="saveAndNext" @click="submitAndAddNext" type="primary">保存并新增下一条</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    name: "index",
    props: {
      title: {
        type: String,
        default: '',
      },
      dialogWidth: {
        type: String,
        default: '500px',
      },
      labelWidth: {
        type: String,
        default: '150px',
      },
      saveAndNext: {
        type: Boolean,
        default: false,
      },
    },
    data(){
      return{
        formDialog: false,
        // width: this.dialogWidth,
        form: {},
        labelList: [],
        rules: {},
        buttonGroup: [],
        headers: {
          Authorization: localStorage.token
        },
        action: process.env.VUE_APP_BASE_API + 'xhc/upload?action=uploadimage',
        inputRuleArr: ['input'],
        selectRuleArr: ['select', 'image', 'multipleSelect', 'date'],
      }
    },
    methods: {
      /**
       * 添加
       **/
      showDialog(labelList){
        this.labelList = labelList;
        this.formDialog = true;
        this.$nextTick(()=>{
          this.$refs.form.clearValidate()
        })
      },
      /**
       * 表单详情
       **/
      showForm(form, labelList){
        this.form = form;
        this.labelList = labelList;
        this.formDialog = true;
      },
      /**
       * 关闭表单弹窗
       **/
      closeDialog(){
        // 重置表单
        this.$refs.form.resetFields();
        this.form = {};
        this.labelList = {};
        this.formDialog = false
      },
      /**
       * 重置表单
       **/
      resetForm(){
        this.$refs.form.resetFields();
      },
      /**
       * 按钮点击
       **/
      cancel(){
        this.formDialog = false;
      },
      submit(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$emit('submit', this.form)
          } else {
            return false
          }
        })
      },
      submitAndAddNext(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$emit('submitAndAddNext', this.form)
          } else {
            return false
          }
        })
      },
      /**
       * 下拉框选择
       **/
      change(val, item){
        this.$forceUpdate();
        this.$emit('selectChange', val, item);
      },
      /**
       * 多选下拉框选择
       **/
      multipleChange(val, item){
        this.$forceUpdate();
        this.$emit('multipleChange', val, item);
      },
      /**
       * 图片上传
       **/
      handleImgSuccess(res, file, fileList, index){
        this.$set(this.form, this.labelList[index]['prop'], '');
        this.form[this.labelList[index]['prop']] = res.data;
        this.$emit('handleImgSuccess', res, file);
      },

      /**
       * 移除图片
       **/
      imageRemove(index){
        this.$set(this.form, this.labelList[index]['prop'], '');
        this.form[this.labelList[index]['prop']] = '';
      },
      /**
       * 图片上传之前
       **/
      beforeImgUpload (file) {
        const isJPG = ['image/jpg', 'image/jpeg', 'image/png'].indexOf(file.type);
        const isLt2M = file.size / 1024 / 1024 < 3;
        if (isJPG < 0) {
          this.$message.error('图片只能是 JPG、PNG 格式');
          return false;
        }
        // if (!isLt2M) {
        //   this.$message.error('图片大小不能超过 3MB!');
        //   return false;
        // }
        return isJPG && isLt2M;
      },
      /**
       * 清空下拉列表
       **/
      clearSelect(model){
        this.form[model] = undefined;
      },
      changeDate(val){
        this.$emit('changeDate', val)
      },
    }
  }
</script>

<style scoped lang="scss">
  .avatar {
    width: 100px;
  }
  .avatar-uploader,
  .preview-img {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    // overflow: hidden;
    width: 100px;
    height: 100px;
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 100px;
      height: 100px;
      line-height: 100px;
      text-align: center;
    }
    .avatar {
      position: absolute;
      top: 50%;
      width: 100px;
      transform: translate(0, -50%);
    }
  }
  .image-upload-wrap{
    width: 100px;
    height: 100px;
    overflow: hidden;
  }
  .el-icon-remove {
    position: absolute;
    top: -7px;
    left: 95px;
    font-size: 18px;
    color: #ed6161;
    cursor: pointer;
    z-index: 10;
  }
</style>
